package com.xyhy.core.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import com.xyhy.core.utils.web.IpUtil;

import java.nio.charset.Charset;

@Slf4j
public class AddressUtil {
  // IP地址查询
  public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
  public static final String UNKNOWN = "未知地址";

  public static String getRealAddressByIP(String ip) {
    // 内网不查询
    if (IpUtil.internalIp(ip)) {
      return "内网IP";
    }
    try {
      String url = String.format("%s?ip=%s&json=true", IP_URL, ip);
      String rspStr = HttpUtil.get(url, Charset.forName("GBK"));
      if (StrUtil.isBlank(rspStr)) {
        log.error("获取地理位置异常 {}", ip);
        return UNKNOWN;
      }
      JSONObject obj = JSONUtil.parseObj(rspStr);
      String region = obj.getStr("pro");
      String city = obj.getStr("city");
      return String.format("%s %s", region, city);
    } catch (Exception e) {
      log.error("获取地理位置异常 {}", ip);
    }
    return UNKNOWN;
  }
}
